# -*- coding: utf-8 -*-
# author: sixmillions
# date: 2022/04/18

"""
调用百度OCR
通用文字识别-高精度版本
需要安装
conda install requests
"""
import base64
import os
import time
from datetime import datetime

import requests


def baidu_ocr(img_path):
    print(datetime.now())

    start = time.time()
    # 获取access_token
    # client_id 为官网获取的AK， client_secret 为官网获取的SK
    appid = os.environ.get('BAIDU_OCR_APPID')
    client_id = os.environ.get('BAIDU_OCR_AK')
    client_secret = os.environ.get('BAIDU_OCR_SK')
    print("appid:" + appid)
    print("client_id:" + client_id)
    print("client_secret:" + client_secret)

    token_url = "https://aip.baidubce.com/oauth/2.0/token"
    host = f"{token_url}?grant_type=client_credentials&client_id={client_id}&client_secret={client_secret}"

    response = requests.get(host)
    access_token = response.json().get("access_token")
    print("当前token：", access_token)

    # 调用通用文字识别高精度版接口
    request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic"
    # 以二进制方式打开图文件
    # 参数image：图像base64编码
    with open(img_path, "rb") as f:
        image = base64.b64encode(f.read())

    body = {
        "image": image,
        "language_type": "auto_detect",
        "detect_direction": "true",
        "paragraph": "true",
        "probability": "true",
    }
    headers = {"Content-Type": "application/x-www-form-urlencoded"}
    request_url = f"{request_url}?access_token={access_token}"
    response = requests.post(request_url, headers=headers, data=body)
    content = response.content.decode("UTF-8")
    # 打印调用结果
    print(content)

    end = time.time()
    print(f"Running time: {(end - start):.2f} Seconds")
    res_dict = eval(content)
    print(type(res_dict), res_dict)
    word_list = res_dict['words_result']
    print(type(word_list), word_list)
    if not word_list:
        return '6666'
    return word_list[0]['words']


if __name__ == '__main__':
    ocr_code = baidu_ocr(r'./5373.png')
    print('识别结果:', ocr_code)
